package com.example.stlink.activitys.fragmentChild.activityTeaHome;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.example.stlink.R;
import com.example.stlink.fragments.DidNotSignListFragment;
import com.example.stlink.fragments.LeaveListFragment;
import com.example.stlink.fragments.SignListFragment;
import com.example.stlink.model.constants.ModelFieldConstants;
import com.example.stlink.model.constants.UrlConstants;
import com.example.stlink.model.request.CourseCreateSignRequest;
import com.example.stlink.model.response.BaseResponse;
import com.example.stlink.model.response.data.CourseSignMsg;
import com.example.stlink.utils.CommonUtils;
import com.example.stlink.utils.QRCodeUtil;
import com.example.stlink.utils.activityUtil.CheckCourseSignUtil;
import com.example.stlink.utils.httpUtils.GetUrlParamHttpUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.internal.LinkedTreeMap;

import java.util.ArrayList;
import java.util.List;

public class CheckCourseSign extends AppCompatActivity {

    private ImageView abIvTitle;
    private TextView aTvCourseName;
    private TextView tvCourseNameMsg;
    private TextView tvCourseTeaNameMsg;
    private TextView tvCourseStuAmountMsg;
    private TextView tvCourseStuArriveAmountMsg;
    private TextView tvCourseStuLeaveAmountMsg;
    private ImageView ivCode;


    private CheckCourseSignUtil checkCourseSignUtil;

    private CourseSignMsg courseSignMsg;

    private Bundle bundle;
    private Handler handler;

    private Handler shareImageHandler;
    private static ActivityResultLauncher<Intent> intentActivityResultLauncher;

    Dialog dialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tea_check_course_sign);
        initView();
        initPage();
    }

    private void initView(){
        CommonUtils.changeStatusBar(CheckCourseSign.this);


        ivCode = findViewById(R.id.iv_code);
        abIvTitle = findViewById(R.id.ab_iv_title);
        aTvCourseName = findViewById(R.id.ab_tv_course_name);
        tvCourseNameMsg = findViewById(R.id.tv_course_name_msg);
        tvCourseTeaNameMsg = findViewById(R.id.tv_course_tea_name_msg);
        tvCourseStuAmountMsg = findViewById(R.id.tv_course_stu_amount_msg);
        tvCourseStuArriveAmountMsg = findViewById(R.id.tv_course_stu_arrive_amount_msg);
        tvCourseStuLeaveAmountMsg = findViewById(R.id.tv_course_stu_leave_amount_msg);

        checkCourseSignUtil = new CheckCourseSignUtil(this.getWindow().getDecorView(),CheckCourseSign.this);

        dialog = new Dialog(this, android.R.style.Theme_Black_NoTitleBar_Fullscreen);

        setClickListener();

        refreshData();

        handler = new Handler(msg -> {
            if(msg.arg1 == 200){
                aTvCourseName.setText(courseSignMsg.getCourseName());
                tvCourseStuAmountMsg.setText(String.valueOf(courseSignMsg.getCourseNum()));
            }
            return false;
        });
        getCourseSignMsg();

        shareImageHandler = new Handler(msg -> {
            if(msg.arg1 == 200){
                Intent shareIntent = (Intent) msg.obj;
                System.out.println("Here...............shareImageHandler.....");
                startActivity(Intent.createChooser(shareIntent, "分享图片"));
            }
            return false;
        });

        // 意图函数加载器
        intentActivityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            Intent data = result.getData();
            int resultCode = result.getResultCode();
            System.out.println("registerForActivityResult...........................");
            if (resultCode == Activity.RESULT_OK) {
                System.out.println("图片分享成功。。。。");
            }
        });
    }

    private void refreshData(){
        bundle = getIntent().getExtras();
        String courseName = bundle.getString(ModelFieldConstants.NOW_SIGN_COURSE_NAME);
        if(!TextUtils.isEmpty(courseName)){
            aTvCourseName.setText(courseName);
        }
        String teaName = bundle.getString(ModelFieldConstants.REAL_NAME);
        if(!TextUtils.isEmpty(teaName)){
            tvCourseTeaNameMsg.setText(teaName);
        }
        Object obj =  bundle.getSerializable(ModelFieldConstants.COURSE_CREATE_SIGN_REQUEST);
        if(obj instanceof CourseCreateSignRequest ){
            CourseCreateSignRequest courseCreateSignRequest = (CourseCreateSignRequest) obj;
            String signCode = String.valueOf(courseCreateSignRequest.getSignCode());
            Bitmap codeBitmap = QRCodeUtil.createQRCode(signCode,500,500,null);
            ivCode.setImageBitmap(codeBitmap);
        }

    }

    private void setClickListener(){
        abIvTitle.setOnClickListener(v -> finish());
        ivCode.setOnClickListener(v -> {
            ivCode.setVisibility(View.INVISIBLE);
            View view = LayoutInflater.from(CheckCourseSign.this).inflate(R.layout.dialog_image, null);
            ImageView ivCodeBig = view.findViewById(R.id.iv_code_big);
            ivCodeBig.setImageDrawable(ivCode.getDrawable());
            dialog.setContentView(view);
            dialog.show();
            ivCodeBig.setOnClickListener(v1 -> {
                dialog.dismiss();
                ivCode.setVisibility(View.VISIBLE);
            });
            ivCodeBig.setOnLongClickListener(v12 -> {
                shareImage();
                return true;
            });
        });
        ivCode.setOnLongClickListener(v -> {
            shareImage();
            return true;
        });
    }

    /**
     * 绑定viewpager2
     */
    private void initPage(){
        List<Fragment> list = new ArrayList<>();
        SignListFragment signListFragment = SignListFragment.newInstance("已签到", this);
        DidNotSignListFragment didNotSignListFragment = DidNotSignListFragment.newInstance("未签到", this);
        LeaveListFragment leaveListFragment = LeaveListFragment.newInstance("请假列表", this);
        list.add(signListFragment);
        list.add(didNotSignListFragment);
        list.add(leaveListFragment);
        checkCourseSignUtil.initPage(list);
    }

    /**
     * 获取签到页面信息
     */
    private void getCourseSignMsg(){
        bundle = getIntent().getExtras();
        Long courseId = bundle.getLong(ModelFieldConstants.NOW_SIGN_COURSE_ID);
        Long userId = bundle.getLong(ModelFieldConstants.ID);
        new Thread(new Runnable() {
            final String urlParam = ModelFieldConstants.COURSE_ID + "=" + courseId + "&" +
                    ModelFieldConstants.USER_ID + "=" + userId;
            final String url = UrlConstants.TEACHER_PAGE + "?" + urlParam;
            @Override
            public void run() {
                new GetUrlParamHttpUtils() {
                    @Override
                    public void nextMethod(BaseResponse<Object> baseResponse) {
                        System.out.println("courseDataBaseResponse.getData() = " + baseResponse.getData() + "...............");

                        //解析数据
                        Gson gson = new GsonBuilder().enableComplexMapKeySerialization().create();
                        Object obj = baseResponse.getData();
                        LinkedTreeMap<String, String> courseDataMap = null;
                        if(obj instanceof LinkedTreeMap){
                            courseDataMap = (LinkedTreeMap<String, String>) obj;
                        }
                        //将LinkedTreeMap中字段映射到CourseData类中
                        courseSignMsg = new CourseSignMsg();
                        String jsonString = gson.toJson(courseDataMap);
                        courseSignMsg = gson.fromJson(jsonString, CourseSignMsg.class);

                        System.out.println("CheckCourseSign:courseData = " + courseSignMsg);

                        Message message = new Message();
                        message.arg1 = 200;
                        handler.sendMessage(message);
                    }

                    @Override
                    public void failedMethod(BaseResponse<Object> baseResponse) { }
                }.getConnect(url);
            }
        }).start();
    }

    /**
     * 分享二维码图片
     */
    private void shareImage(){
        new Thread(() -> {
            Intent shareIntent = new Intent();
            shareIntent.setAction(Intent.ACTION_SEND);
            shareIntent.setType("image/*");  //设置分享内容的类型
            Uri uri = Uri.parse(MediaStore.Images.Media.insertImage(getContentResolver(), getBitmap(ivCode.getDrawable()), null,null));
            shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
            Message message = new Message();
            message.arg1 = 200;
            message.obj = shareIntent;
            shareImageHandler.sendMessage(message);
        }).start();
    }

    /**
     * 从drawable获取BitMap
     * @param drawable 从ImageView中获取的
     * @return 返回BitMap
     */
    private Bitmap getBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(
                drawable.getIntrinsicWidth(),
                drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888
                        : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        //canvas.setBitmap(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }
}
